#!/usr/bin/env bash

RETVAL=0

current_version=$2
max_version=0

platform=`uname`

http_domain=xxxx.service.worm.org

# 尝试创建安装目录
function _init_install() {
    mkdir -p /usr/local/worm
    mkdir -p /usr/local/worm/agent
}

# 获取当前的最新的版本号
function _get_max_version() {
    max_version=`wget --timeout=2 -t 3 -O- -q https://${http_domain}:8080/worm/client/max_ver?platform=${platform}
    --no-check-certificate 2>/dev/null`
    if [ -z ${max_version} ]; then
        echo "wget worm client max version file error."
        exit 1
    fi
}

# 停止 agent
function stop_agent() {
    # 停止当前版本
    current_version_dir="/usr/local/worm/agent/${current_version}/control.sh"
    if [ -f "$current_version_dir" ]; then
        ${current_version_dir} stop
        echo 0
    fi
    echo 0
}

function restart_agent() {
    # 停止当前版本
    current_version_dir="/usr/local/worm/agent/${current_version}/control.sh"
    if [ -f "$current_version_dir" ]; then
        ${current_version_dir} stop
    fi

    max_version_agent="/usr/local/worm/agent/${max_version}/agent"
    echo "$max_version_agent"
    if [ -f "$max_version_agent" ]; then
        # 直接启动
        echo "start worm agent ..."
        cd /usr/local/worm/agent/${max_version_agent}/
        ./control.sh start
        echo 0
    else
        echo "install $max_version worm agent ..."
        cd /usr/local/worm/agent

        package_name=worm_agent..${max_version}.${platform}.tar.gz
        echo "getint package name: ${package_name}"

        rm ${package_name}
        sleep 1
        # https的方式
        wget --timeout=2 -t 3 https://${http_domain}:8122/worm/worm/${package_name} --no-check-certificate 2>/dev/null
        # 分析
        file_name=`echo ${package_name} | awk '{split($0, arr, ".");print arr[1];}'`
        echo ${file_name}
        file_version=`echo ${package_name} | awk '{split($0, arr, ".");print arr[2];}'`
        echo ${file_version}

        echo "install begin ..."
        # 创建安装目录
        mkdir -p ${file_version}
        mv ${package_name} ${file_version}/${package_name}
        cd ${file_version}
        tar -zxf ${package_name}

        ./control.sh start
        echo 0
    fi
}

function start_agent() {
    restart_agent
}

function use_help() {
    echo "$0 start|stop|restart [current_version]"
}

echo "**********************"
if [ "$1" == "" ]; then
    use_help                            # 帮助信息
elif [ "$1" == "stop" ];then
    stop_agent                          # 停止程序
elif [ "$1" == "start" ];then
    _init_install
    _get_max_version
    start_agent                         # 启动agent
elif [ "$1" == "restart" ];then
    _init_install
    _get_max_version
    restart_agent                       # 重启agent
else
    use_help
fi

RETVAL=$?

exit $RETVAL